package com.jeffgalper.feather;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public abstract class AbstractFeatherable implements Featherable {

   public ByteBuffer getEPathBytes() throws FeatherException {
      return ByteBuffer.wrap(getEPathToArray());
   }

   public byte[] getEPathToArray() throws FeatherException {
      try {
         return getUPath().getBytes("UTF-16LE");
      } catch (UnsupportedEncodingException e) {
         throw new FeatherException("Cannot encode file path");
      }
   }

   public ByteBuffer getEPathSizeBytes() throws FeatherException {
      ByteBuffer buffer = ByteBuffer.allocate(Short.SIZE
            / Feather.BITS_PER_BYTE);
      buffer.putShort(getEPathSize());
      buffer.rewind();
      return buffer;
   }

   public ByteBuffer getFileSizeBytes() throws FeatherException {
      ByteBuffer buffer = ByteBuffer
            .allocate(Long.SIZE / Feather.BITS_PER_BYTE);
      buffer.putLong(getFileSize());
      buffer.rewind();
      return buffer;
   }

   public short getEPathSize() throws FeatherException {
      int size = getEPathBytes().capacity();
      if (size > Short.MAX_VALUE)
         throw new FeatherException(
               "Path cannot fit in feather file: length of " + size
                     + " is greater than max length of " + Short.MAX_VALUE);
      return (short) size;
   }

   public ByteBuffer getBitField() {
      return ByteBuffer.wrap(new byte[] { getBitFieldByte() });
   }

   public byte getBitFieldByte() {
      byte flag = 0;
      if (isDirectory()) {
         flag |= 1;
      }
      return flag;
   }
}
